package day14;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;

/**
 * @author oldliu
 * @since 1.0
 */
public class XMLAdd {
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        System.out.println("请输入要zengjia的课程名称难度，序号和描述:");
        String name=in.nextLine();
        String diff=in.nextLine();
        int index=in.nextInt();
        in.nextLine();
        String desc=in.nextLine();
        SAXReader reader = new SAXReader();
        Document doc = null;
        try {
            //XMLRead.class.getClassLoader().getResourceAsStream("day14/demo.xml");
            doc = reader.read(XMLRead.class.getClassLoader().getResourceAsStream("day14/books.xml"));
            //doc = reader.read(new FileInputStream("java高级\\src\\day14\\demo.xml"));
        } catch (Exception e) {
            e.printStackTrace();
            //return;
            System.out.println("创建了新的文档对象！");
            doc= DocumentHelper.createDocument();
            //增加一个根节点
            doc.addElement("books");
        }

        Element root = doc.getRootElement();
        Element newBook = root.addElement("book");
        newBook.addAttribute("index",String.valueOf(index));
        Element ename = newBook.addElement("name");
        ename.setText(name);
        Element df = newBook.addElement("difficult");
        df.setText(diff);
        Element miaoshu = newBook.addElement("des");
        miaoshu.setText(desc);

        try {
            OutputFormat format=OutputFormat.createPrettyPrint();
            format.setEncoding("utf-8");
            XMLWriter xm=new XMLWriter(new FileOutputStream("java高级\\src\\day14\\books.xml"),format);
            xm.write(doc);
            xm.close();
        }  catch (Exception e) {
            e.printStackTrace();
        }
    }
}
